package cn.kgc.spring.jdbc.mapper;

import cn.kgc.spring.jdbc.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/4/26
 */
@Repository
public class StudentMapperImpl implements StudentMapper {
    @Autowired
    private JdbcTemplate jdbcTemplate;  // spring对jdbc封装的实体类

    //查询一个学生对象  id
    @Override
    public Student selectOne(int id) {
        String sql = "select  *  from student where id = ?";
        //BeanPropertyRowMapper    实现查询结果的自动映射
        Student student = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Student>(Student.class), id);
        return student;
    }


    public List<Student> selectAll() {
        String sql = "select  *  from student";
        //BeanPropertyRowMapper    实现查询结果的自动映射
        List<Student> students = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        return students;
    }

    @Override
    public int selectTotal() {
        //查询总的记录条数
        String sql = "select count(*) from student";
        Integer count = jdbcTemplate.queryForObject(sql, int.class);
        return count;
    }

    @Override
    public int addStudent(Student student) {
        String sql = "insert into student (stu_name,age,score,birth,create_time)values(?,?,?,?,?)";
        int line = jdbcTemplate.update(sql, student.getStuName(), student.getAge(), student.getScore(), student.getBirth(), student.getCreateTime());
        return line;
    }

    @Override
    public int updateStudent(Student student) {
        String sql = "update student set stu_name = ? where id = ?";
        int line = jdbcTemplate.update(sql, student.getStuName(), student.getId());
        return line ;
    }

    @Override
    public int delStudent(int id) {
        String sql = "delete from student  where id = ?";
        int line = jdbcTemplate.update(sql,id);
        return line ;
    }

}
